package com.example.mqttcar.mqtt;

import com.example.mqttcar.util.PropertiesLoader;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Properties;

@Component
public class MqttSubscriber {

    public static String broker = "";
    public static String clientId = "";
    public static String topic = "";
    public static String username = "";
    public static String password = "";

    public static String messageToWeb = "";


//    @PostConstruct
//    public void initProperties(){
//        Properties prop = PropertiesLoader.load("mqtt.properties");
//        broker = prop.getProperty("broker");
//        clientId = prop.getProperty("clientId");
//        topic = prop.getProperty("topic");
//        username = prop.getProperty("username");
//        password = prop.getProperty("password");
//    }

    @Bean
    public MqttClient mqttClient() throws MqttException {
        // 加载配置
        Properties prop = PropertiesLoader.load("mqtt.properties");
        broker = prop.getProperty("broker");
        clientId = prop.getProperty("clientId");
        topic = prop.getProperty("topic");
        username = prop.getProperty("username");
        password = prop.getProperty("password");

        // 1. 创建客户端
        MqttClient client = new MqttClient(
                broker,
                clientId
        );

        // 2. 设置回调
        client.setCallback(new MqttCallback() {
            @Override
            public void messageArrived(String topic, MqttMessage message) {
                //这边可以在参数中判断是外部服务发送的消息还是内部服务发送消息
                //这个回调是不管是哪边发送消息，都能接收到该主题的消息

                messageToWeb = new String(message.getPayload());
                System.out.println("收到消息: " + new String(message.getPayload()));
            }

            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("连接断开: " + cause.getMessage());
                while (!client.isConnected()){
                    try {
                        System.out.println("尝试重新连接......");
                        client.connect();
                        client.subscribe(topic);
                        System.out.println("重新连接成功");
                        break;
                    }catch (MqttException  e){
                        System.err.println("重连失败: " + e.getMessage());
                        try {
                            Thread.sleep(5000); // 等待5秒后重试
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {}
        });

        // 3. 连接并订阅
        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true); // 启用自动重连
        options.setMaxReconnectDelay(5000);  // 最大重连间隔(毫秒)
        options.setCleanSession(false);     // 保持会话状态
//        options.setUserName(username);
//        options.setPassword(password);
        client.connect(options);
        client.subscribe(topic);

        return client;
    }
}
